from odoo import api, models, fields, _


class SmrpWorkorderBackorderWizard(models.TransientModel):
    _name = 's.mrp.workorder.backorder.wizard'

    production_id = fields.Many2one('mrp.production', string='MO')
    # is_all_subcontracting = fields.Boolean(string='是否全部外包(包工包料)')
    line_ids = fields.One2many('s.mrp.workorder.backorder.line.wizard', 'wizard_id')
    unlink_line_ids = fields.One2many('s.mrp.workorder.backorder.line.wizard', 'unlink_wizard_id')
    workorder_ids = fields.Many2many('mrp.workorder', string='工序')

    def action_confirm(self):
        if not self.workorder_ids:
            self._all_subcontracting()
            self.production_id.product_id.purchase_ok = True
            self._create_subcontracting_apply()
        else:
            pass

    def _all_subcontracting(self):
        """包工包料外发
        1、取消工单，以及内层工单
        2、自动生成半成品采购
        """
        mrp_prods = self.production_id
        mrp_prods |= self._get_child_mrp(self.production_id)
        mrp_prods.write({'state': 'cancel'})

    def _get_child_mrp(self, mrp):
        child_ids = mrp._get_children()
        # 欠单
        mrp_backorders = mrp.procurement_group_id.mrp_production_ids
        return child_ids | mrp_backorders

    def _create_subcontracting_apply(self):
        """自动生成外发申请，并自动审批"""

        workflow= self.env.ref('sb_subcontracting.product_subcontracting_workflow')
        if self.production_id.product_id.seller_ids:
            seller_ids = self.production_id.product_id.seller_ids.sorted(lambda x : x.write_date, reverse=True)[0]
            partner_id = seller_ids.partner_id.id
            purchase_price = seller_ids.price
        else:
            purchase_price = 0
            partner_id = None

        apply_vals = {
            'sb_workflow_template_id': workflow.id,
            'is_all_outside': True,
            'line_ids': [(0, 0, {
                'production_id': self.production_id.id,
                'product_id': self.production_id.product_id.id,
                'qty_wip': self.production_id.product_qty,
                'done_act_qty': self.production_id.product_qty,
                'remark': '包工包料半成品采购',
                'price_unit': purchase_price,
                'partner_id': partner_id
            })]
        }
        apply = self.env['sb.subcontracting.apply'].create(apply_vals)
        apply.create_workflow()


class SmrpWorkorderBackorderLineWizard(models.TransientModel):
    _name = 's.mrp.workorder.backorder.line.wizard'

    is_unlink = fields.Boolean(default=False, help="删除工序")
    is_add = fields.Boolean(default=False, help='新增工序')
    is_update = fields.Boolean(default=False, help='修改工序')
    wizard_id = fields.Many2one('s.mrp.workorder.backorder.wizard')
    unlink_wizard_id = fields.Many2one('s.mrp.workorder.backorder.wizard')

    workorder_id = fields.Many2one('mrp.workorder')
    step = fields.Integer(string='Step', related='workorder_id.step')
    work_station_id = fields.Many2one('work.station', related='workorder_id.work_station_id',string='Work Station')

    def unlink(self):
        """set unlink"""
        self.is_unlink = True

    def c_unlink(self):
        """cancel unlink"""
        self.is_unlink = False


